package com.qdlc.p2p.dal.common;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.qdlc.p2p.dal.dao.NoticeTypeDao;
import com.qdlc.p2p.dal.dto.NoticeType;

/**
 * 通知类型操作类，通知类型分为短信通知、邮箱通知、站内信通知。
 * 通知指定一个通知类型nid，也就是noticeTypeNid，来获取到具体的通知类型NoticeType，在NoticeType保存着通知类型和发送通知的模版内容。
 * 一个noticeTypeNid可能对应到多个NoticeType记录。
 * 
 * @author linya
 */
@Service
public class NoticeTypeHelper implements ApplicationContextAware{

	/**
	 * 通知类型:短信、邮箱、站内信
	 */
	public static enum NidType {
		
		NOTICE_SMS(1),		//短信
		NOTICE_EMAIL(2),	//邮箱
		NOTICE_MESSAGE(3);	//站内信
		
		int type;
		
		static List<NidType> allNidType = Arrays.asList(NidType.values());
		
		private NidType(int type) {
			this.type = type;
		}
		int getType(){
			return type;
		}
		public static List<NidType> getNitTypeList(){
			return allNidType;
		}
	}
	
	private static final Map<String, NoticeType> noticeTypeMap = new ConcurrentHashMap<String, NoticeType>();
	
	public static NoticeType getValue(String noticeTypeNid, NidType nidType){
		String key = wrapKey(noticeTypeNid, nidType.getType());
		NoticeType noticeType = noticeTypeMap.get(key);
		return noticeType;
	}
	
	private void initial(ApplicationContext context){
		NoticeTypeDao noticeTypeDao = context.getBean(NoticeTypeDao.class);
		List<NoticeType> noticeTypeList = noticeTypeDao.list();
		if(noticeTypeList == null){
			return;
		}
		for (NoticeType noticeType: noticeTypeList) {
			noticeTypeMap.put(wrapKey(noticeType.getNid(), noticeType.getNoticeType()), noticeType);
		}
	}
	
	private static String wrapKey(String nid, int nidType){
		return nid + "_" + nidType;
	}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		initial(applicationContext);
	}

}
